package com.stn.zjx.givingtreasure.activity.web;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.stn.zjx.givingtreasure.R;
import com.stn.zjx.givingtreasure.base.BaseActivity;
import com.stn.zjx.givingtreasure.event.NetWorkEvent;
import com.stn.zjx.givingtreasure.service.UserService;
import com.stn.zjx.givingtreasure.widget.WebViewJavaScriptFunction;
import com.stn.zjx.givingtreasure.widget.X5WebView;
import com.tencent.smtt.sdk.CookieManager;
import com.tencent.smtt.sdk.CookieSyncManager;
import com.tencent.smtt.sdk.DownloadListener;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.white.progressview.HorizontalProgressView;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class GenericWebActivity extends BaseActivity {


    @BindView(R.id.back_bt)
    RelativeLayout backBt;
    @BindView(R.id.action_title)
    TextView actionTitle;
    @BindView(R.id.action_add_bt)
    RelativeLayout actionAddBt;
    @BindView(R.id.webView)
    X5WebView webView;
    @BindView(R.id.progress)
    HorizontalProgressView progress;
    @BindView(R.id.web_title)
    TextView webTitle;
    @BindView(R.id.action_refresh)
    RelativeLayout actionRefresh;
    @BindView(R.id.exit)
    RelativeLayout exit;
    private String url = "";

    public ValueCallback<Uri[]> uploadFiles;
    public ValueCallback<Uri> uploadFile;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_generic_web);
        ButterKnife.bind(this);
        initComponent();
    }


    public void initWebView() {
        webView.setWebChromeClient(new WebChromeClient() {

            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> valueCallback, FileChooserParams fileChooserParams) {
                uploadFiles = valueCallback;
                return true;

            }


            @Override
            public void onReceivedTitle(WebView webView, String s) {
                super.onReceivedTitle(webView, s);
                webTitle.setText(s);
            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                // TODO Auto-generated method stub
                super.onProgressChanged(view, newProgress);
                if (newProgress == 100) {
                    progress.setVisibility(View.GONE);
                } else {
                    progress.setProgress(newProgress);
                    progress.setVisibility(View.VISIBLE);
                }
            }
        });
        webView.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                String tag = "tel:";

                if (url.contains(tag)) {
                    Uri uri = Uri.parse(url);
                    Intent intent = new Intent(Intent.ACTION_CALL, uri);
                    if (ActivityCompat.checkSelfPermission(GenericWebActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(GenericWebActivity.this, new String[]{Manifest.permission.CALL_PHONE}, 100);
                        return true;
                    }
                    startActivity(intent);
                    //这个超连接,java已经处理了，webview不要处理了
                    return true;
                } else {
                    view.loadUrl(url);
                }

                return true;
            }
        });


        webView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            }
        });

        webView.addJavascriptInterface(new WebViewJavaScriptFunction() {
            @Override
            public void onJsFunctionCalled(String tag) {
            }

            @SuppressWarnings("unused")
            @JavascriptInterface
            public void toTotalAssets(String url) {


            }


        }, "Android");
        Map<String, String > map = new HashMap<String, String>() ;
        if(UserService.getInstance(this).getOnlineLoginUser()!=null){
            map.put("token",UserService.getInstance(this).getOnlineLoginUser().getToken());
        }
        webView.loadUrl(url,map);
        System.out.println("********************" + url);
//        CookieSyncManager.createInstance(this);
//        CookieSyncManager.getInstance().sync();
    }


    @OnClick({R.id.back_bt,R.id.action_refresh,R.id.exit})
    public void onMyClick(View view) {
        switch (view.getId()) {
            case R.id.back_bt:
                if (webView.canGoBack()) {
                     webView.goBack();// 返回前一个页面
                  return;
                 }
                finish();
                break;
            case R.id.action_refresh:
               webView.reload();
                break;
            case R.id.exit:
                finish();
                break;
        }
    }


    private void openFileChooseProcess() {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        startActivityForResult(Intent.createChooser(i,
                "Image Chooser"), 0);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 0:
                    if (uploadFiles != null) {
                        if (resultCode == RESULT_OK && data.getData() != null) {
                            uploadFiles.onReceiveValue(new Uri[]{data.getData()});
                            uploadFiles = null;
                        }
                    }
                    if (uploadFile != null) {
                        if (resultCode == RESULT_OK && data.getData() != null) {
                            uploadFile.onReceiveValue(data.getData());
                            uploadFile = null;
                        }
                    }
                    break;
                default:
                    if (uploadFiles != null) {
                        uploadFiles.onReceiveValue(null);
                    }
                    uploadFiles = null;
                    break;

            }
        } else if (resultCode == RESULT_CANCELED) {
            if (uploadFiles != null) {
                uploadFiles.onReceiveValue(null);
            }
            uploadFiles = null;
        }
    }

    @Override
    public void networkStatus(NetWorkEvent netWorkEvent) {

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        initClearAll();

    }

    @Override
    public void initComponent() {
        actionTitle.setText("");
        actionTitle.setVisibility(View.GONE);
        webTitle.setVisibility(View.VISIBLE);
        actionRefresh.setVisibility(View.VISIBLE);
        exit.setVisibility(View.VISIBLE);
        url = getIntent().getStringExtra("url");
        initWebView();
    }

    public void initClearAll() {
        //清空所有Cookie
//        CookieSyncManager.createInstance(this);  //Create a singleton CookieSyncManager within a context
//        CookieManager cookieManager = CookieManager.getInstance(); // the singleton CookieManager instance
//        cookieManager.removeAllCookie();// Removes all cookies.
//        CookieSyncManager.getInstance().sync(); // forces sync manager to sync now
//        webView.clearCache(true);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
            webView.goBack();// 返回前一个页面
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
